package hash_map_set;

/**
 * Created with IntelliJ IDEA.
 * Description: 简单的哈希桶 ： 数组 + 链表
 * User: 86187
 * Date: 2022-08-21
 * Time: 22:15
 */

public class HashBuck {

    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] elem;
    public int usedSize; //有效数据个数
    public static final float DEFAULT_LOAD_FACTOR = 0.75F; //hash 负载因子


    public HashBuck() {
        this.elem = new Node[10];
        this.usedSize = 0;
    }

    /**
     *  存储 key 和 val
     */
    public void put(int key, int val) {

        int index = key % elem.length;
        Node newNode = new Node(key, val);

        Node cur = elem[index];
        while(cur != null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //头插法
        newNode.next = elem[index];
        elem[index] = newNode;
        usedSize++;

        if(loadFactor() >= DEFAULT_LOAD_FACTOR) {
            //进行扩容
            growSize();
        }
    }

    private float loadFactor() {
        return 1.0F * usedSize / elem.length;
    }
    private void growSize() {
        Node[] newElem = new Node[elem.length*2];
        /**
         *  1.遍历数组的每个元素的链表
         *  2.每遍历一个节点 就重新哈希 key % newElem.length
         *  3.进行头插法
         */
        for (int i = 0; i < elem.length; i++) {
            Node cur = elem[i];
            while(cur != null) {
                //找到新的位置
                int index = cur.key % newElem.length;
                Node nextNode = cur.next;

                //头插
                cur.next = newElem[index];
                newElem[index] = cur;

                cur = nextNode;
            }
        }
        this.elem = newElem;
    }

    /**
     *  通过 key 获取 val的值
     */
    public int get(int key) {
        int index = key % elem.length;

        Node cur = elem[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
